import axios, {
  Method,
  ResponseType,
  AxiosRequestConfig,
  Canceler,
} from "axios";
import qs from "qs";
import router from "../router/index";
import { error } from "../common/message";
import { ElLoading } from "element-plus";
import "element-plus/theme-chalk/el-loading.css";
interface DataConfig {
  code?: number;
  data?: any;
  message?: string;
}

interface RequestConfig {
  method: Method;
  url: string;
  params?: any;
  data?: any;
  headers?: any;
  dataType?: ResponseType;
  timeout?: number;
  unloading?: boolean;
}

const CancelToken = axios.CancelToken;
let cancel: Canceler;
const service = axios.create({
  timeout: 20_000,
  paramsSerializer: function (p) {
    return qs.stringify(p, { arrayFormat: "repeat" });
  },
});

let loading: any = null;

service.defaults.baseURL = import.meta.env.VITE_BASE_URL as string;

// 请求拦截
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    loading = ElLoading.service({
      target: ".main-content",
      fullscreen: true,
      lock: true,
    });
    //配置token
    const token = localStorage.getItem("token");
    config.headers = {
      Authorization: token || "",
    };
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  (response) => {
    loading.close();
    return response;
  },
  (error) => {
    if (axios.isCancel(error)) {
      return { data: { msg: "canceled" } };
    }
    if (error.response) {
      switch (error.response.code) {
      }
    }
    loading.close();
    return Promise.reject(error.response.code);
  }
);

export function request(options: RequestConfig): Promise<any> {
  const header = options.headers || {
    "Content-Type": "application/json; charset=UTF-8",
  };
  return new Promise((resolve, reject) => {
    service({
      cancelToken: new CancelToken((c) => {
        cancel = c;
      }),
      method: options.method,
      url: options.url,
      params: options.params || {},
      data:
        (options.headers &&
        options.headers["Content-Type"].indexOf("x-www-form-urlencoded") >= 0
          ? JSON.stringify(options.data)
          : options.data) || {},
      responseType: options.dataType,
      headers: header,
      timeout: options.timeout || 20_000,
    })
      .then((res) => res.data)
      .then((data: DataConfig) => {
        if (data?.code == 200) {
          resolve(data.data);
        } else if (data?.code == 804) {
          localStorage.removeItem("token");
          router.push("/login");
        } else {
          error(data.message ?? "错误提交");
          reject(data);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}

export default request;
